﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using WoSoft.PACS.Data.CheckData;
using WoSoft.PACS.Data.DepartmentDoctor;
using WoSoft.PACS.Data.TemplateData;
using WoSoft.PACS.Document;
using DevComponents.DotNetBar.SuperGrid;
using System.Runtime.InteropServices;
using DevComponents.DotNetBar.Controls;
using WoSoft.PACS.Win.Properties;
using Microsoft.Reporting.WinForms;
using WoSoft.PACS.Win.MyClass;
using System.Data;
using WoSoft.PACS.Win.MyControlsNew;

namespace WoSoft.PACS.Win.Forms.SubForms
{
    /// <summary>
    /// 检查报告
    /// </summary>
    public partial class FrmCheckReportNewIn : FrmBase
    {
        //病人检查申请ID
        private string _checkappID;
        //病人检查类型
        private string _checkappType;
        //检查访问对象
        private CheckApp _checkapp;

        private bool IsSave = true;//是否已经保存

        FrmCapture frmCapture = null;//图像采集界面
        FrmCaptureNew FrmCaptureNew = null;//图像采集界面
        FrmDicomView frmDicomView = null;//DicomView查看器

        private OutlineCategoryDataService outlineCategoryDs = new OutlineCategoryDataService();
        private OutlineWordsDataService outlineWordsDs = new OutlineWordsDataService();
        private TemplateDataService _templateDataService = new TemplateDataService();

        private ElementModel elementModel = new ElementModel();

        public FrmCheckReportNewIn(string checkappid, string checktype)
        {
            InitializeComponent();
            _checkappID = checkappid;
            _checkappType = checktype;
            _checkapp = new CheckApp();
        }

        //加载信息
        private void FrmCheckReport_Load(object sender, EventArgs e)
        {
            splitContainer_Left.SplitterDistance = Settings.Default.Left_Point;
            splitContainer_Top.SplitterDistance = Settings.Default.Top_Point;

            //删除公共多余的图片，保留最近10张
            _checkapp.DeletePublicImage();

            if (!Settings.Default.SavePublicImg)//删除公共区域图片
            {
                _checkapp.DeletePublicImageAll();
            }

            //加载图像
            LoadImages_Public("");

            //加载采集窗口
            if (Settings.Default.CameraHardware == "New")
            {
                ShowCaptureNew();
            }
            else
            {
                ShowCapture();
            }

            if (!string.IsNullOrEmpty(this._checkappID))
            {
                //加载提纲
                LoadOutline(this._checkappType);

                //加载图像
                LoadImages_Private(this._checkappID);

                //加载图像
                LoadImages_Public(this._checkappID);

                //加载报告
                LoadReport(this._checkappID);

                //加载病人信息
                LoadPatientInfos(this._checkappID);
            }
        }

        //加载报告
        private void LoadReport(string checkappID)
        {
            dynamic obj = _checkapp.GetCheckReport(checkappID);
            if (obj != null)//已经保存过的报告记录
            {
                TextBox1.Text = obj.检查印象;
                TextBox2.Text = obj.诊断建议;
                TextBox3.Text = obj.检查备注;
            }
            else
            {
                TextBox1.Text = "";
                TextBox2.Text = "";
                TextBox3.Text = "";
            }
        }

        //加载病人信息
        private void LoadPatientInfos(string checkappID)
        {
            dynamic obj = _checkapp.GetAppCheckInfo(checkappID);
            if (obj != null)//已经保存过的报告记录
            {
                //加载病人检查信息
                var text1 = "{0}病人     申请单号：{1}     姓名：{2}    年龄：{3}岁   性别:{4}    申请医生：{5}   申请医生：{6}  申请时间：{7}";
                var text2 = "检查类型：{0}     检查项目：{1}         临床诊断：{2}";

                var appType = obj.申请来源;
                var appNum = obj.申请单号;         //申请单号
                var name = obj.姓名;
                var age = obj.年龄;
                var sex = obj.性别;
                int sex1 = Convert.ToInt32(obj.性别);
                switch (sex1)
                {
                    case 1:
                        sex = "男";
                        break;
                    case 2:
                        sex = "女";
                        break;
                    default:
                        sex = "不详";
                        break;
                }

                var fromDepartment = obj.申请科室; //来源科室
                var appdoc = obj.申请医生;         //申请医生
                var apptime = obj.申请时间;        //申请时间

                text1 = string.Format(text1, appType, appNum, name, age, sex, fromDepartment, appdoc, apptime);
                this.lblInfo1.Text = text1;

                var appItems = obj.检查类型;           //检查类型
                var diagnosis = obj.检查项目名称;      //检查项目
                var checkAim = obj.临床诊断;           //临床诊断
                text2 = string.Format(text2, appItems, diagnosis, checkAim);

                this.lblInfo2.Text = text2;

                IsSave = true;
            }
        }

        //加载提纲与词句
        private void LoadOutline(string checkappType)
        {
            var dt = outlineCategoryDs.GetAllDataBy(checkappType);

            this.advTree1.DisplayMembers = "名称";
            this.advTree1.ValueMember = "ID";
            this.advTree1.DataSource = dt;
            this.advTree1.ParentFieldNames = "ID,上级ID";
            this.advTree1.ExpandAll();
        }

        //加载检查图像
        public void LoadImages_Public(string _checkappID)
        {
            //加载图像信息(清除面板内容)
            imgPanls.Controls.Clear();

            var imgList = _checkapp.GetImage_Temp(_checkappID);
            if (imgList != null && imgList.Count > 0)
            {
                foreach (var imgModel in imgList)
                {
                    if (imgModel.ImageBytes != null)
                    {
                        var bmp = ByteToImage(imgModel.ImageBytes);
                        //写入文件中
                        SaveToFile(imgModel.ImageBytes, imgModel.ID, imgModel.CaptureTime);

                        PictureBox pic = new PictureBox();
                        pic.ContextMenuStrip = this.contextMenuStrip;
                        pic.Dock = DockStyle.Top;
                        //pic.Height = 150;
                        pic.Height = capPanls.Height;
                        pic.Name = imgModel.ID;
                        pic.Padding = new System.Windows.Forms.Padding(5);
                        pic.Margin = new System.Windows.Forms.Padding(5);
                        pic.Image = bmp;
                        pic.BorderStyle = BorderStyle.FixedSingle;
                        pic.SizeMode = PictureBoxSizeMode.StretchImage;
                        pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);
                        pic.MouseDown += new MouseEventHandler(pic_MouseDown);

                        //显示编辑按钮
                        var imgEditButton = new Button();
                        imgEditButton.Name = "imgEditBtn";
                        imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                        imgEditButton.Width = 20;
                        imgEditButton.Height = 20;
                        imgEditButton.BackColor = Color.Transparent;
                        imgEditButton.Location = new Point(25, 5);
                        imgEditButton.Click += new EventHandler(imgEditButton_Click);
                        pic.Controls.Add(imgEditButton);

                        //显示编辑与删除按钮
                        var delButton_Public = new Button();
                        delButton_Public.Name = "delBtn";
                        delButton_Public.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                        delButton_Public.Width = 20;
                        delButton_Public.Height = 20;
                        delButton_Public.BackColor = Color.Transparent;
                        delButton_Public.Location = new Point(5, 5);
                        delButton_Public.Click += new EventHandler(delButton_Public_Click);
                        pic.Controls.Add(delButton_Public);

                        imgPanls.Controls.Add(pic);
                        IsSave = false;
                    }
                }
            }
        }

        //加载检查图像
        public void LoadImages_Private(string _checkappID)
        {
            //加载图像信息(清除面板内容)
            panelBoxImage.Controls.Clear();

            var imgList = _checkapp.GetImage(_checkappID);
            if (imgList != null && imgList.Count > 0)
            {
                foreach (var imgModel in imgList)
                {
                    if (imgModel.ImageBytes != null)
                    {
                        var bmp = ByteToImage(imgModel.ImageBytes);
                        //写入文件中
                        SaveToFile(imgModel.ImageBytes, imgModel.ID, imgModel.CaptureTime);

                        PictureBox pic = new PictureBox();
                        //pic.ContextMenuStrip = this.contextMenuStrip;
                        pic.Dock = DockStyle.Left;
                        //pic.Width = 200;
                        pic.Width = this.capPanls.Width / 2; ;
                        pic.Name = imgModel.ID;
                        pic.Padding = new System.Windows.Forms.Padding(5);
                        pic.Margin = new System.Windows.Forms.Padding(5);
                        pic.Image = bmp;
                        pic.BorderStyle = BorderStyle.FixedSingle;
                        pic.SizeMode = PictureBoxSizeMode.StretchImage;
                        //pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);


                        //显示编辑按钮
                        var imgEditButton = new Button();
                        imgEditButton.Name = "imgEditBtn";
                        imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                        imgEditButton.Width = 20;
                        imgEditButton.Height = 20;
                        imgEditButton.BackColor = Color.Transparent;
                        imgEditButton.Location = new Point(25, 5);
                        imgEditButton.Click += new EventHandler(imgEditButton_Click);
                        pic.Controls.Add(imgEditButton);

                        //显示编辑与删除按钮
                        var delButton_Private = new Button();
                        delButton_Private.Name = "delBtn";
                        delButton_Private.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                        delButton_Private.Width = 20;
                        delButton_Private.Height = 20;
                        delButton_Private.BackColor = Color.Transparent;
                        delButton_Private.Location = new Point(5, 5);
                        delButton_Private.Click += new EventHandler(delButton_Private_Click);
                        pic.Controls.Add(delButton_Private);

                        panelBoxImage.Controls.Add(pic);
                    }
                }
            }
        }
        void imgEditButton_Click(object sender, EventArgs e)
        {
            PictureBox pic = (sender as Button).Parent as PictureBox;
            var frmImageEdit = new FrmImageEdit(pic.Image, _checkappID,pic.Name);
            frmImageEdit.StartPosition = FormStartPosition.CenterScreen;
            //frmImageEdit.Show(this);
            if (frmImageEdit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LoadImages_Private(this._checkappID);
            }
        }

        void pic_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Middle)
            {
                PictureBox pic = sender as PictureBox;
                var frmImageEdit = new FrmImageEdit(pic.Image, _checkappID,pic.Name);
                frmImageEdit.StartPosition = FormStartPosition.CenterScreen;
                //frmImageEdit.Show(this);
                if (frmImageEdit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    LoadImages_Private(this._checkappID);
                }
            }
        }

        //删除图像
        void delButton_Private_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Parent.GetType().ToString() == "System.Windows.Forms.PictureBox")
            {
                var r = MessageBoxEx.Show("您确认要删除选中的图像吗?", "删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (r == DialogResult.OK)
                {
                    this.panelBoxImage.Controls.Remove((sender as Button).Parent);
                    //数据库删除
                    this._checkapp.DeleteImage((sender as Button).Parent.Name, _checkappID);
                    IsSave = false;
                }
            }
        }

        //删除图像
        void delButton_Public_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Parent.GetType().ToString() == "System.Windows.Forms.PictureBox")
            {
                var r = MessageBoxEx.Show("您确认要删除选中的图像吗?", "删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (r == DialogResult.OK)
                {
                    this.imgPanls.Controls.Remove((sender as Button).Parent);
                    //数据库删除
                    this._checkapp.DeleteImage_Temp((sender as Button).Parent.Name, _checkappID);
                    IsSave = false;
                }
            }
        }

        //保存图像到文件中
        private void SaveToFile(byte[] data, string id, DateTime createTime)
        {
            try
            {
                var timeFolder = createTime.ToString("yyyyMMdd");
                var imgPath = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder, id + ".jpg");
                var imgFolder = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder);
                if (!File.Exists(imgPath))
                {//文件不存在,则创建
                    if (!Directory.Exists(imgFolder))
                    {//检查文件目录是否存在,不存在,则创建
                        Directory.CreateDirectory(imgFolder);
                    }
                    using (MemoryStream ms1 = new MemoryStream(data))
                    {
                        Image.FromStream(ms1).Save(imgPath);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //保存记录到数据库中
        private void SaveToDB()
        {
            if (string.IsNullOrEmpty(this._checkappID)) return;
            _checkapp.SaveReport(_checkappID, null, FrmMain.CurrentUser.Name, TextBox1.Text, TextBox2.Text, TextBox3.Text);
            IsSave = true;
        }

        //双击图像
        void pic_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (string.IsNullOrEmpty(this._checkappID)) return;
            var picbox = sender as PictureBox;

            picbox.Enabled = false;//00000000000000000
            if (picbox != null)
            {
                var imgName = picbox.Name;
                var path = Path.Combine(Application.StartupPath, "CaptureImages");
                var files = Directory.GetFiles(path, imgName + ".jpg", SearchOption.AllDirectories);

                //保存图像(到数据库)
                var dat = FileToByte(files[0]);
                this._checkapp.SaveImage(imgName, this._checkappID, dat);

                //刷新,重新加载图像
                LoadImages_Private(this._checkappID);
            }
            picbox.Enabled = true;//0000000000000000000
        }

        //工具栏单击事件
        private void tlsReport_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "tlsCheckApp":
                    CheckApp(e);
                    break;
                case "tlsEdit":
                    PatientEdit(e);
                    break;
                case "tlsPatientSelect":
                    PatientSelect(e);
                    break;
                case "tlsSave":         //保存到数据库中
                    SaveToDB();
                    break;
                case "tlsPrint":
                    SaveToDB();
                    Print();
                    break;
                case "tlsPrintView":
                    if (string.IsNullOrEmpty(this._checkappID)) return;
                    FrmReportView frm = new FrmReportView(this._checkappID, this._checkappType);
                    frm.ShowDialog();
                    break;
                case "tlsScreenCapture":
                    ScreenCapture(e);
                    break;
                case "tlsDicom":
                    ShowDicomView();
                    break;
                case "tlsClose":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        //检查申请登记
        private void CheckApp(ToolStripItemClickedEventArgs e)
        {
            SubForms.FrmCheckAppNew appCheckForm = new SubForms.FrmCheckAppNew();
            if (appCheckForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this._checkappID = appCheckForm.AppCheckID;
                this._checkappType = appCheckForm.AppCheckType;

                //加载提纲
                LoadOutline(this._checkappType);

                //加载图像
                LoadImages_Private(this._checkappID);

                //加载报告
                LoadReport(this._checkappID);

                //加载病人信息
                LoadPatientInfos(this._checkappID);

                //清空公共区域图像
                if (!Settings.Default.SavePublicImg)//删除图片
                {
                    _checkapp.DeletePublicImageAll();
                    imgPanls.Controls.Clear();
                }
            }
        }

        //信息修改
        private void PatientEdit(ToolStripItemClickedEventArgs e)
        {
            if (string.IsNullOrEmpty(this._checkappID)) return;

            SubForms.FrmCheckAppNew appCheckForm = new SubForms.FrmCheckAppNew();
            appCheckForm.AppCheckID = this._checkappID;

            if (appCheckForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this._checkappID = appCheckForm.AppCheckID;
                this._checkappType = appCheckForm.AppCheckType;

                //加载提纲
                LoadOutline(this._checkappType);

                //加载图像
                //LoadImages_Private(this._checkappID);

                //加载报告
                //LoadReport(this._checkappID);

                //加载病人信息
                LoadPatientInfos(this._checkappID);
            }
        }

        //病人选择
        private void PatientSelect(ToolStripItemClickedEventArgs e)
        {
            if (!IsSave && !string.IsNullOrEmpty(this._checkappID))//没有保存过
            {
                DialogResult dialogResult = MessageBoxEx.Show("报告信息没有保存，是否保存？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    SaveToDB();
                }
            }

            SubForms.FrmPatientSelect frmPatientSelect = new SubForms.FrmPatientSelect();
            if (frmPatientSelect.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this._checkappID = frmPatientSelect.AppCheckID;
                this._checkappType = frmPatientSelect.AppCheckType;

                //加载提纲
                LoadOutline(this._checkappType);

                //加载图像
                LoadImages_Private(this._checkappID);

                //加载报告
                LoadReport(this._checkappID);

                //加载病人信息
                LoadPatientInfos(this._checkappID);

                //清空公共区域图像
                if (!Settings.Default.SavePublicImg)//删除图片
                {
                    _checkapp.DeletePublicImageAll();
                    imgPanls.Controls.Clear();
                }

                //加载图像_临时
                LoadImages_Public(this._checkappID);
            }
        }

        //屏幕截图
        private void ScreenCapture(ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "开启屏幕截图")
            {
                System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("ScreenCutter");
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    myProcess.Kill();
                }
                Process.Start(Application.StartupPath + @"\ScreenCutter.exe");
                e.ClickedItem.Text = "关闭屏幕截图";
            }
            else
            {
                System.Diagnostics.Process[] myProcesses= System.Diagnostics.Process.GetProcessesByName("ScreenCutter");
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    myProcess.Kill();
                }
                e.ClickedItem.Text = "开启屏幕截图";
            }
        }

        private void Print()
        {
            if (string.IsNullOrEmpty(this._checkappID)) return;

            //wordDoc.Print();

            LocalReport report = new LocalReport();
            DataTable dt = _checkapp.GetReportResult(this._checkappID);

            int imgCounts = _checkapp.ImgCounts(this._checkappID);
            if (imgCounts == 1)
                report.ReportPath = Application.StartupPath + @"/RdlcReport/" + this._checkappType + "1.rdlc";
            else if (imgCounts == 2)
                report.ReportPath = Application.StartupPath + @"/RdlcReport/" + this._checkappType + "2.rdlc";
            else if (imgCounts == 3)
                report.ReportPath = Application.StartupPath + @"/RdlcReport/" + this._checkappType + "3.rdlc";
            else
                report.ReportPath = Application.StartupPath + @"/RdlcReport/" + this._checkappType + "4.rdlc";


            report.EnableExternalImages = true;
            //ReportParameter rp1 = new ReportParameter("tjdw", str_tjdw);
            //ReportParameter rp2 = new ReportParameter("barcode", str_path);
            //ReportParameter rp3 = new ReportParameter("sqd_ts", sqd_ts);
            report.DataSources.Clear();
            //report.SetParameters(new ReportParameter[] { rp1, rp2, rp3 });
            report.DataSources.Add(new ReportDataSource("DataSet检查报告记录", dt));

            RdlcPrintNew rdlcprint = new RdlcPrintNew();
            if (!rdlcprint.Run(report, "报告打印", false, "A4", true)) return;//超过一页提示是否继续

            //打印后自动完成状态
            _checkapp.Update_State(_checkappID, 4);

            //更新打印状态
            _checkapp.Update_SfPrint(_checkappID, 1);

            //标识阳性结果                   
            DialogResult dialogResult = MessageBoxEx.Show("结果是否阳性", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
                _checkapp.Update_Sfyx(_checkappID, 1);
            else
                _checkapp.Update_Sfyx(_checkappID, 0);
            //this.Close();//打印后自动关闭
        }

        //值变化事件
        private void advTree1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (this.advTree1.SelectedValue != null)
            {
                var _selectCategoryID = this.advTree1.SelectedValue.ToString();

                var dt = outlineWordsDs.GetModesByCID(_selectCategoryID);
                this.superGridControl1.PrimaryGrid.DataSource = dt;
            }
        }

        //行双击事件
        private void superGridControl1_RowDoubleClick(object sender, DevComponents.DotNetBar.SuperGrid.GridRowDoubleClickEventArgs e)
        {
            if (this.superGridControl1.PrimaryGrid.Rows.Count > 0)
            {

                var _selectCategoryID = object.Equals(this.advTree1.SelectedNode.Parent, null) ? "" : this.advTree1.SelectedNode.Parent.Text;  //检查备注

                var gridRow = e.GridRow as GridRow;
                if (gridRow != null)
                {
                    if (_selectCategoryID == "检查备注")
                    {
                        if (TextBox3.Text.Trim() != "")
                        {
                            TextBox3.AppendText(Environment.NewLine + gridRow["colContent"].Value.ToString());
                        }
                        else
                        {
                            TextBox3.Text = gridRow["colContent"].Value.ToString();
                        }
                    }
                    else
                    {
                        if (TextBox1.Text.Trim() != "")
                        {
                            TextBox1.AppendText(Environment.NewLine + gridRow["colContent"].Value.ToString());
                        }
                        else
                        {
                            TextBox1.Text = gridRow["colContent"].Value.ToString();
                        }

                        if (TextBox2.Text.Trim() != "")
                        {
                            TextBox2.AppendText(Environment.NewLine + gridRow["colRemark"].Value.ToString());
                        }
                        else
                        {
                            TextBox2.Text = gridRow["colRemark"].Value.ToString();
                        }
                    }
                }
            }
        }

        private void 导入IToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(_checkappID)) return;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "打开(Open)";
            ofd.FileName = "";
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);//为了获取特定的系统文件夹，可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举，其中可以定义要返回路径的哪个系统目录
            ofd.Filter = "JPG图片|*.jpg|BMP图片|*.bmp|Gif图片|*.gif";// "JPG图片|*.jpg|BMP图片|*.bmp|Gif图片|*.gif";
            ofd.ValidateNames = true;     //文件有效性验证ValidateNames，验证用户输入是否是一个有效的Windows文件名
            ofd.CheckFileExists = true;  //验证路径有效性
            ofd.CheckPathExists = true; //验证文件有效性
            try
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string ID = Guid.NewGuid().ToString();
                    PictureBox pic = new PictureBox();
                    pic.ContextMenuStrip = this.contextMenuStrip;
                    pic.Name = ID;
                    pic.Dock = DockStyle.Top;
                    pic.Height = 150;
                    pic.Padding = new System.Windows.Forms.Padding(15);
                    pic.Margin = new System.Windows.Forms.Padding(3);
                    pic.ImageLocation = ofd.FileName;
                    pic.BorderStyle = BorderStyle.FixedSingle;
                    pic.SizeMode = PictureBoxSizeMode.StretchImage;
                    pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);
                    pic.MouseDown += new MouseEventHandler(pic_MouseDown);

                    //保存图像(到数据库)
                    var dat = FileToByte(ofd.FileName);
                    this._checkapp.SaveImage_Temp(ID, this._checkappID, dat);//保存到公共区域

                    //显示编辑按钮
                    var imgEditButton = new Button();
                    imgEditButton.Name = "imgEditBtn";
                    imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                    imgEditButton.Width = 20;
                    imgEditButton.Height = 20;
                    imgEditButton.BackColor = Color.Transparent;
                    imgEditButton.Location = new Point(25, 5);
                    imgEditButton.Click += new EventHandler(imgEditButton_Click);
                    pic.Controls.Add(imgEditButton);

                    //显示编辑与删除按钮
                    var delButton_Public = new Button();
                    delButton_Public.Name = "delBtn";
                    delButton_Public.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                    delButton_Public.Width = 20;
                    delButton_Public.Height = 20;
                    delButton_Public.BackColor = Color.Transparent;
                    delButton_Public.Location = new Point(5, 5);
                    delButton_Public.Click += new EventHandler(delButton_Public_Click);
                    pic.Controls.Add(delButton_Public);

                    this.imgPanls.Controls.Add(pic);
                    IsSave = false;
                    //复制到文件中
                    try
                    {
                        var timeFolder = DateTime.Now.ToString("yyyyMMdd");
                        var imgPath = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder, ID + ".jpg");
                        var imgFolder = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder);
                        if (!File.Exists(imgPath))
                        {//文件不存在,则创建
                            if (!Directory.Exists(imgFolder))
                            {//检查文件目录是否存在,不存在,则创建
                                Directory.CreateDirectory(imgFolder);
                            }
                            File.Copy(ofd.FileName, imgPath, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void 导出OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (contextMenuStrip.SourceControl.GetType().ToString() == "System.Windows.Forms.PictureBox")
            {
                PictureBox pictureBox = contextMenuStrip.SourceControl as PictureBox;

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "导出图像";
                saveFileDialog.Filter = "JPG图片|*.jpg|BMP图片|*.bmp|Gif图片|*.gif";
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                if ((saveFileDialog.ShowDialog()) == DialogResult.OK)
                {
                    //复制到文件中
                    if (saveFileDialog.FileName != null)
                    {
                        try
                        {
                            var timeFolder = DateTime.Now.ToString("yyyyMMdd");
                            var imgPath = Path.Combine(Application.StartupPath, "CaptureImages", timeFolder, pictureBox.Name + ".jpg");
                            File.Copy(imgPath, saveFileDialog.FileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message.ToString());
                        }
                    }
                }
            }
        }


        private void ShowCapture()
        {
            if (object.Equals(frmCapture, null))
            {
                frmCapture = new FrmCapture("");
                //Size size = new Size(this.capPanls.Width, this.capPanls.Height);
                //frmCapture.Size = size;
                frmCapture.Dock = DockStyle.Fill;
                frmCapture.FormBorderStyle = FormBorderStyle.None;
                frmCapture.TopLevel =false; //指示子窗体非顶级窗体
                this.capPanls.Controls.Add(frmCapture);//将子窗体载入panel
                frmCapture.Show();
            }
        }

        private void ShowCaptureNew()
        {
            if (object.Equals(FrmCaptureNew, null))
            {
                FrmCaptureNew = new FrmCaptureNew();
                //Size size = new Size(this.capPanls.Width, this.capPanls.Height);
                //frmCapture.Size = size;
                FrmCaptureNew.Dock = DockStyle.Fill;
                FrmCaptureNew.FormBorderStyle = FormBorderStyle.None;
                FrmCaptureNew.TopLevel = false; //指示子窗体非顶级窗体
                this.capPanls.Controls.Add(FrmCaptureNew);//将子窗体载入panel
                FrmCaptureNew.Show();
            }
        }

        const int WM_COPYDATA = 0x004A;

        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        // 接收窗体间消息    
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            bool WatchPortMsg = true;
            switch (m.Msg)
            {
                //接收自定义消息 USER，并显示其参数
                case WM_COPYDATA:
                    if (WatchPortMsg)
                    {
                        COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                        Type mytype = mystr.GetType();
                        mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                        try
                        {
                            PictureBox pic = new PictureBox();
                            pic.ContextMenuStrip = this.contextMenuStrip;
                            pic.Name = mystr.lpData.Split('|')[0];
                            pic.Dock = DockStyle.Top;
                            pic.Height = 150;
                            pic.Padding = new System.Windows.Forms.Padding(15);
                            pic.Margin = new System.Windows.Forms.Padding(3);
                            pic.ImageLocation = mystr.lpData.Split('|')[1];
                            pic.BorderStyle = BorderStyle.FixedSingle;
                            pic.SizeMode = PictureBoxSizeMode.StretchImage;
                            pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick);
                            pic.MouseDown += new MouseEventHandler(pic_MouseDown);

                            //保存图像(到数据库)
                            var dat = FileToByte(mystr.lpData.Split('|')[1]);
                            this._checkapp.SaveImage_Temp(mystr.lpData.Split('|')[0], this._checkappID, dat);

                            //显示编辑按钮
                            var imgEditButton = new Button();
                            imgEditButton.Name = "imgEditBtn";
                            imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                            imgEditButton.Width = 20;
                            imgEditButton.Height = 20;
                            imgEditButton.BackColor = Color.Transparent;
                            imgEditButton.Location = new Point(25, 5);
                            imgEditButton.Click += new EventHandler(imgEditButton_Click);
                            pic.Controls.Add(imgEditButton);

                            //显示编辑与删除按钮
                            var delButton_Public = new Button();
                            delButton_Public.Name = "delBtn";
                            delButton_Public.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                            delButton_Public.Width = 20;
                            delButton_Public.Height = 20;
                            delButton_Public.BackColor = Color.Transparent;
                            delButton_Public.Location = new Point(5, 5);
                            delButton_Public.Click += new EventHandler(delButton_Public_Click);
                            pic.Controls.Add(delButton_Public);

                            this.imgPanls.Controls.Add(pic);
                        }
                        catch { }
                        //switch (mystr.lpData)
                        //{
                        //    case "refresh":
                        //        LoadImages();//刷新列表
                        //        break;
                        //    default:
                        //        break;
                        //}
                    }
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        private void ShowDicomView()
        {
            if (object.Equals(frmDicomView, null))
            {
                frmDicomView = new FrmDicomView(_checkappID);
                frmDicomView.Show(this);
            }
            else
            {
                frmDicomView.Hide();
                frmDicomView.Dispose();
                frmDicomView = null;
                //加载图像  刷新
                LoadImages_Public("");
            }
        }

        private void FrmCheckReport_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Settings.Default.Width = this.capPanls.Width;
            //Settings.Default.Height = this.capPanls.Height;
            //Settings.Default.Save();

            if (!object.Equals(frmCapture, null))//释放资源
            {
                frmCapture.Close();
                frmCapture.Dispose();
            }
            if (!Settings.Default.SavePublicImg)//删除图片
            {
                _checkapp.DeletePublicImageAll();
            }
        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            IsSave = false;
        }

        private void TextBox2_TextChanged(object sender, EventArgs e)
        {
            IsSave = false;
        }

        private void FrmCheckReportNewIn_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!IsSave && !string.IsNullOrEmpty(this._checkappID))//没有保存过
            {
                DialogResult dialogResult = MessageBoxEx.Show("报告信息没有保存，是否保存？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    SaveToDB();
                }
            }
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("ScreenCutter");
            foreach (System.Diagnostics.Process myProcess in myProcesses)
            {
                myProcess.Kill();
            }
        }

        private void splitContainer_Left_SplitterMoved(object sender, SplitterEventArgs e)
        {
            //MessageBox.Show(splitContainer_Left.SplitterDistance.ToString());
            Settings.Default.Left_Point = splitContainer_Left.SplitterDistance;
            Settings.Default.Save();
        }

        private void splitContainer_Top_SplitterMoved(object sender, SplitterEventArgs e)
        {
            //MessageBox.Show(splitContainer_Top.SplitterDistance.ToString());
            Settings.Default.Top_Point = splitContainer_Top.SplitterDistance;
            Settings.Default.Save();
        }

    }
}
